package com.lishilin.gulimall.product.web;

import com.lishilin.gulimall.product.entity.CategoryEntity;
import com.lishilin.gulimall.product.service.CategoryService;

import com.lishilin.gulimall.product.vo.CateLog2VO;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate redisTemplate;

    //配置无论访问localhost：port/ 或者 localhost:port/index.html 都跳转至index.html首页
    @GetMapping({"/","index.html"})
    public String indexPage(Model model){
        // TODO: 2022/03/08 查出所有的一级分类
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Cagegorys();
        long l1 = System.currentTimeMillis();
        System.out.println(l1-l);
        //thymeleaf 自动配置了前缀和后缀 .html
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody//将返回的值以json格式返回出去  而不是以页面的方式
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<CateLog2VO>> getCatalogJson () {

        Map<String, List<CateLog2VO>> map = categoryService.getCatalogJson();

        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        //2.加锁
        lock.lock(10, TimeUnit.SECONDS);//阻塞式等待
        //锁的自动续期，如果业务过长，运行期间自动给锁续上新的时间 默认为30s
        //加锁的业务只要运行完成，就不会给当前锁续期，及时不手动解锁，锁默认在30s以后自动删除
        //2.1如果我们传递了超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //2.2如果我们未指定锁的超时时间，就使用30*1000 localwathcdogTIme看门狗的默认时间
        //2.3只要占锁成功，就会启动一个定时任务，重新给锁设置过期时间，新的过期时间为看门狗的默认时间
        //定时任务的时间为 10s

        //最好还是使用指定时间来加锁，这样就可以省掉续期操作，手动进行解锁  lock.lock(10, TimeUnit.SECONDS);
        try {
            System.out.println("加锁成功，执行业务");
            Thread.sleep(3000);
        }catch (Exception e) {

        }finally {
            System.out.println("释放锁："+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    //保证一定能读到最新数据，修改期间，不能够读取
    //写锁没释放，读就必须等待
    //读+读：相当于无所，并发读，只会在redis中记录好，所有当前的读锁
    //写+读：必须得等待写锁释放
    //写+写：等待上一个写完成，才能进入下一个写
    //读+写：等待读的完成，才能够写
    //只要是有写入锁的存在，都必须等待
    @GetMapping("/write")
    @ResponseBody
    public String wreiteValue () {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            //1.改数据加写锁，读数据加读锁
            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(15000);
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {

        }finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue () {
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String writeValue = "";
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            writeValue = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        return writeValue;
    }

    /*
    * 放假锁门
    * 必须等待所有班级都走完了，才能够锁门
    * */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor () throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);//计数器
        door.await();//等待闭锁完成

        return "锁门完成";
    }

    @GetMapping("gogogo/{id}")
    @ResponseBody
    public String gogogo (@PathVariable("id") Long id) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//计数减1
        return id+"班的人走完了";
    }

    /*
    * 车库停车 3个车位 来一辆车给一个提示 走一辆车给一个提示
    * */
    @GetMapping("/park")
    @ResponseBody
    public String park () throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();//获取一个信号，获取一个值，占一个车位
        return "ok";
    }
    @GetMapping("/go")
    @ResponseBody
    public String go () {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();
        return "离开了车位";
    }


}
